// cpu
<template>
  <div>
    <!-- CPU 利用率 -->
    <div class="bg-fff pAll mb_10 contentList">
      <div class="header">
        <span>CPU 利用率</span>
        <ul>
          <li>最新值：{{ list3.utilization.last }} %</li>
          <li>最小值：{{ list3.utilization.min }} %</li>
          <li>平均值：{{ list3.utilization.avg }} %</li>
          <li>最大值：{{ list3.utilization.max }} %</li>
        </ul>
      </div>
      <div style="height: 300px">
        <echarts-load v-if="DlFlag3 || reload_Dl3" :chartFlag="DlFlag3" :reload="reload_Dl3" @refreshF="refreshDl3" />
        <div v-else>
          <div>
            <cpu-line :chartsData="echartData3" />
          </div>
        </div>
      </div>
    </div>
    <!-- CPU 占有率 -->
    <div class="bg-fff pAll mb_10 contentList">
      <div class="header">
        <span>CPU 占有率</span>
      </div>
      <div style="height: 395px">
        <echarts-load v-if="DlFlag1 || reload_Dl1" :chartFlag="DlFlag1" :reload="reload_Dl1" @refreshF="refreshDl1" />
        <div v-else>
          <el-row class="toggleList">
            <el-col :span="6">
              <div class="toggleItem">
                <h2>软中断处理时间(softirq time)</h2>
                <el-row class="item_param">
                  <el-col :span="12">
                    <div>
                      <p>最新值：{{ list1.softirqTime.last }} %</p>
                      <p>平均值：{{ list1.softirqTime.avg }} %</p>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div>
                      <p>最小值：{{ list1.softirqTime.min }} %</p>
                      <p>最大值：{{ list1.softirqTime.max }} %</p>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="toggleItem">
                <h2>I/O等待时间(iowait time)</h2>
                <el-row class="item_param">
                  <el-col :span="12">
                    <div>
                      <p>最新值：{{ list1.ioWaitTime.last }} %</p>
                      <p>平均值：{{ list1.ioWaitTime.avg }} %</p>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div>
                      <p>最小值：{{ list1.ioWaitTime.min }} %</p>
                      <p>最大值：{{ list1.ioWaitTime.max }} %</p>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="toggleItem">
                <h2>用户时间(user time)</h2>
                <el-row class="item_param">
                  <el-col :span="12">
                    <div>
                      <p>最新值：{{ list1.userTime.last }} %</p>
                      <p>平均值：{{ list1.userTime.avg }} %</p>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div>
                      <p>最小值：{{ list1.userTime.min }} %</p>
                      <p>最大值：{{ list1.userTime.max }} %</p>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="toggleItem">
                <h2>系统时间(system time)</h2>
                <el-row class="item_param">
                  <el-col :span="12">
                    <div>
                      <p>最新值：{{ list1.systemTime.last }} %</p>
                      <p>平均值：{{ list1.systemTime.avg }} %</p>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div>
                      <p>最小值：{{ list1.systemTime.min }} %</p>
                      <p>最大值：{{ list1.systemTime.max }} %</p>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-col>
          </el-row>
          <div>
            <!-- <echarts-load v-if="DlFlag1 || reload_Dl1" :chartFlag="DlFlag1" :reload="reload_Dl1" @refreshF="refreshDl1" /> -->
            <!-- <cpu-line v-else :chartsData="echartData1" /> -->
            <cpu-line :chartsData="echartData1" />
          </div>
        </div>
      </div>
    </div>
    <!-- CPU 平均负载 -->
    <div class="bg-fff pAll mb_10 contentList">
      <div class="header">
        <span>CPU 平均负载</span>
        <ul>
          <li>CPU数量：{{ cpuNumber }}</li>
        </ul>
      </div>
      <div style="height: 395px">
        <echarts-load v-if="DlFlag2 || reload_Dl2" :chartFlag="DlFlag2" :reload="reload_Dl2" @refreshF="refreshDl2" />
        <div v-else>
          <el-row class="toggleList">
            <el-col :span="8">
              <div class="toggleItem">
                <h2>1分钟平均负载 load average（1m avg）</h2>
                <el-row class="item_param">
                  <el-col :span="12">
                    <div>
                      <p>最新值：{{ list2.loadAverage1Min.last }}</p>
                      <p>平均值：{{ list2.loadAverage1Min.avg }}</p>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div>
                      <p>最小值：{{ list2.loadAverage1Min.min }}</p>
                      <p>最大值：{{ list2.loadAverage1Min.max }}</p>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="toggleItem">
                <h2>5分钟平均负载 load average（5m avg）</h2>
                <el-row class="item_param">
                  <el-col :span="12">
                    <div>
                      <p>最新值：{{ list2.loadAverage5Min.last }}</p>
                      <p>平均值：{{ list2.loadAverage5Min.avg }}</p>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div>
                      <p>最小值：{{ list2.loadAverage5Min.min }}</p>
                      <p>最大值：{{ list2.loadAverage5Min.max }}</p>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="toggleItem">
                <h2>15分钟平均负载 load average（15m avg）</h2>
                <el-row class="item_param">
                  <el-col :span="12">
                    <div>
                      <p>最新值：{{ list2.loadAverage15Min.last }}</p>
                      <p>平均值：{{ list2.loadAverage15Min.avg }}</p>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div>
                      <p>最小值：{{ list2.loadAverage15Min.min }}</p>
                      <p>最大值：{{ list2.loadAverage15Min.max }}</p>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-col>
          </el-row>
          <div>
            <!-- <echarts-load v-if="DlFlag2 || reload_Dl2" :chartFlag="DlFlag2" :reload="reload_Dl2" @refreshF="refreshDl2" />
          <cpu-line v-else :chartsData="echartData2" /> -->
            <cpu-line :chartsData="echartData2" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { timeLoad } from '@/assets/js/setTime'
import cpuLine from '@/components/Echarts/cloudEcharts/cpuLine'
import echartsLoad from '@/components/Echarts/echartsLoad'
export default {
  data() {
    return {
      DlFlag1: false,
      reload_Dl1: false,
      dlTimer1: null,
      echartData1: {},
      DlFlag2: false,
      reload_Dl2: false,
      dlTimer2: null,
      echartData2: {},
      DlFlag3: false,
      reload_Dl3: false,
      dlTimer3: null,
      echartData3: {},
      searchCondition: {},
      list1: {
        softirqTime: { min: '', avg: '', last: '', max: '' },
        ioWaitTime: { min: '', avg: '', last: '', max: '' },
        userTime: { min: '', avg: '', last: '', max: '' },
        systemTime: { min: '', avg: '', last: '', max: '' },
      },
      list2: {
        loadAverage1Min: { min: '', avg: '', last: '', max: '' }, // 1分钟平均负载
        loadAverage5Min: { min: '', avg: '', last: '', max: '' }, // 5分钟平均负载
        loadAverage15Min: { min: '', avg: '', last: '', max: '' }, // 15分钟平均负载
      },
      list3: {
        utilization: { min: '', avg: '', last: '', max: '' },
      },
      cpuNumber: '',
      initInterval: null,
      childValue: {},
    }
  },
  components: { cpuLine, echartsLoad },
  props: ['childData'],
  watch: {
    DlFlag1(newVal, oldVal) {
      this.dlTimer1 = setTimeout(() => {
        if (this.DlFlag1) {
          this.DlFlag1 = false
          this.reload_Dl1 = true
        }
      }, timeLoad)
    },
    DlFlag2(newVal, oldVal) {
      this.dlTimer2 = setTimeout(() => {
        if (this.DlFlag2) {
          this.DlFlag2 = false
          this.reload_Dl2 = true
        }
      }, timeLoad)
    },
    childData: {
      deep: true,
      handler(newVal, oldVal) {
        this.searchCondition = newVal
        this.initList_findUsage() // CPU 占有率
        this.initList_findAverage() // CPU 平均负载
        this.initList_findUtilization() // CPU 利用率
        if (newVal.type === 'change') {
          clearInterval(this.initInterval)
        }
      },
    },
  },
  created() {
    this.searchCondition = this.childData
    this.initList_findUsage() // CPU 占有率
    this.initList_findAverage() // CPU 平均负载
    this.initList_findUtilization() // CPU 利用率
    if (this.searchCondition.type !== 'change') {
      this.initInterval = setInterval(() => {
        this.getSearchTime()
        this.initList_findUsage() // CPU 占有率
        this.initList_findAverage() // CPU 平均负载
        this.initList_findUtilization() // CPU 利用率
      }, 1000 * 30)
    }
  },
  methods: {
    // 获取时间
    getSearchTime() {
      var difference = new Date(this.searchCondition.endDate).getTime() - new Date(this.searchCondition.startDate).getTime()
      var startDate = this.initTime(new Date(new Date().getTime() - difference))
      var endDate = this.initTime(new Date())
      this.childValue = {
        startDate: startDate, // 开始日期、(yyyy-MM-dd HH:mm:ss)
        endDate: endDate, // 结束日期、(yyyy-MM-dd HH:mm:ss)
        type: '',
      }
      this.$emit('childByValue', this.childValue)
    },
    initTime(date) {
      const Y = date.getFullYear()
      const M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var h = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()
      var m = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()
      var s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds()
      return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s // yyyy-MM-dd HH:mm:ss
    },
    // 获取cpu占有率
    async initList_findUsage() {
      clearTimeout(this.dlTimer1)
      this.DlFlag1 = true
      this.reload_Dl1 = false
      const params = new URLSearchParams()
      params.append('relSerialNo', this.$route.query.relSerialNo) // 主机流水号
      params.append('startDate', this.searchCondition.startDate) // 开始日期、(yyyy-MM-dd HH:mm:ss)
      params.append('endDate', this.searchCondition.endDate) // 结束日期、(yyyy-MM-dd HH:mm:ss)
      const { data: res } = await this.$http.post('snmp/cpuLog/findUsage', params)
      this.DlFlag1 = false
      // this.reload_Dl1 = true
      this.reload_Dl1 = false
      // console.log(res)
      switch (res.code) {
        case '0000':
          var details_arr = res.data.details
          var details_softirqTime = details_arr.softirqTime
          var details_ioWaitTime = details_arr.ioWaitTime
          var details_userTime = details_arr.userTime
          var details_systemTime = details_arr.systemTime
          for (var k in details_softirqTime) {
            details_softirqTime[k] = details_softirqTime[k].toFixed(2)
          }
          for (var x in details_ioWaitTime) {
            details_ioWaitTime[x] = details_ioWaitTime[x].toFixed(2)
          }
          for (var m in details_userTime) {
            details_userTime[m] = details_userTime[m].toFixed(2)
          }
          for (var n in details_systemTime) {
            details_systemTime[n] = details_systemTime[n].toFixed(2)
          }
          // this.list1 = res.data.details
          this.list1 = details_arr
          var xData = []
          var timeList = {
            softirqTime: [], // 软中断处理时间
            ioWaitTime: [], // I/O等待时间
            userTime: [], // 用户时间
            systemTime: [], // 系统时间
          }
          var list = {
            softirqTime: '软中断处理时间(softirq time)',
            ioWaitTime: 'I/O等待时间(iowait time)',
            userTime: '用户时间(user time)',
            systemTime: '系统时间(system time)',
          }
          res.data.list.forEach((item, index) => {
            var time = new Date(item.createDate)
            xData.push(this.getTime(time))
            timeList.softirqTime.push(item.softirqTime.toFixed(2)) // 软中断处理时间
            timeList.ioWaitTime.push(item.ioWaitTime.toFixed(2)) // I/O等待时间
            timeList.userTime.push(item.userTime.toFixed(2)) // 用户时间
            timeList.systemTime.push(item.systemTime.toFixed(2)) // 系统时间
          })
          var seriesDate = []
          for (const k in list) {
            seriesDate.push({
              name: list[k],
              type: 'line',
              // stack: '总量',
              data: timeList[k],
            })
          }
          this.echartData1 = {
            id: 'cpuline1',
            type: 'green',
            xData: xData,
            legendData: ['软中断处理时间(softirq time)', 'I/O等待时间(iowait time)', '用户时间(user time)', '系统时间(system time)'],
            seriesDate: seriesDate,
            unit: ' %',
          }
          break
        default:
          this.echartData1 = {
            id: 'cpuline1',
            type: 'green',
            xData: [],
            legendData: [],
            seriesDate: [],
            unit: ' %',
          }
          this.DlFlag1 = false
          this.reload_Dl1 = true
          break
      }
    },
    refreshDl1() {
      this.reload_Dl1 = false
      this.initList_findUsage()
    },
    // CPU 平均负载
    async initList_findAverage() {
      clearTimeout(this.dlTimer2)
      this.DlFlag2 = true
      this.reload_Dl2 = false
      const params = new URLSearchParams()
      params.append('relSerialNo', this.$route.query.relSerialNo) // 主机流水号
      params.append('startDate', this.searchCondition.startDate) // 开始日期、(yyyy-MM-dd HH:mm:ss)
      params.append('endDate', this.searchCondition.endDate) // 结束日期、(yyyy-MM-dd HH:mm:ss)
      const { data: res } = await this.$http.post('snmp/cpuLog/findAverage', params)
      // console.log(res)
      this.DlFlag2 = false
      this.reload_Dl2 = false
      switch (res.code) {
        case '0000':
          var details_arr = res.data.details
          var details_loadAverage1Min = details_arr.loadAverage1Min
          var details_loadAverage5Min = details_arr.loadAverage5Min
          var details_loadAverage15Min = details_arr.loadAverage15Min
          for (var k in details_loadAverage1Min) {
            details_loadAverage1Min[k] = details_loadAverage1Min[k].toFixed(2)
          }
          for (var x in details_loadAverage5Min) {
            details_loadAverage5Min[x] = details_loadAverage5Min[x].toFixed(2)
          }
          for (var m in details_loadAverage15Min) {
            details_loadAverage15Min[m] = details_loadAverage15Min[m].toFixed(2)
          }
          // this.list2 = res.data.details
          this.list2 = details_arr
          this.cpuNumber = res.data.list[res.data.list.length - 1].cpuNumber // CPU数量
          var xData = []
          var timeList = {
            loadAverage1Min: [],
            loadAverage5Min: [],
            loadAverage15Min: [],
          }
          var list = {
            loadAverage1Min: '1分钟平均负载 load average（1m avg）',
            loadAverage5Min: '5分钟平均负载 load average（5m avg）',
            loadAverage15Min: '15分钟平均负载 load average（15m avg）',
          }
          res.data.list.forEach((item, index) => {
            var time = new Date(item.createDate)
            xData.push(this.getTime(time))
            timeList.loadAverage1Min.push(item.loadAverage1Min.toFixed(2))
            timeList.loadAverage5Min.push(item.loadAverage5Min.toFixed(2))
            timeList.loadAverage15Min.push(item.loadAverage15Min.toFixed(2))
          })
          var seriesDate = []
          for (const k in list) {
            seriesDate.push({
              name: list[k],
              type: 'line',
              // stack: '总量',
              data: timeList[k],
            })
          }
          this.echartData2 = {
            id: 'cpuline2',
            type: 'green',
            xData: xData,
            legendData: ['1分钟平均负载 load average（1m avg）', '5分钟平均负载 load average（5m avg）', '15分钟平均负载 load average（15m avg）'],
            seriesDate: seriesDate,
            unit: '',
          }
          break
        default:
          this.echartData2 = {
            id: 'cpuline2',
            type: 'green',
            xData: [],
            legendData: [],
            seriesDate: [],
            unit: '',
          }
          this.DlFlag2 = false
          this.reload_Dl2 = true
          break
      }
    },
    refreshDl2() {
      this.reload_Dl2 = false
      this.initList_findAverage()
    },
    // CPU 利用率
    async initList_findUtilization() {
      clearTimeout(this.dlTimer2)
      this.DlFlag3 = true
      this.reload_Dl3 = false
      const params = new URLSearchParams()
      params.append('relSerialNo', this.$route.query.relSerialNo) // 主机流水号
      params.append('startDate', this.searchCondition.startDate) // 开始日期、(yyyy-MM-dd HH:mm:ss)
      params.append('endDate', this.searchCondition.endDate) // 结束日期、(yyyy-MM-dd HH:mm:ss)
      const { data: res } = await this.$http.post('snmp/cpuLog/findUtilization', params)
      // console.log(res)
      this.DlFlag3 = false
      this.reload_Dl3 = false
      switch (res.code) {
        case '0000':
          var details_arr = res.data.details
          var details_utilization = details_arr.utilization
          for (var k in details_utilization) {
            details_utilization[k] = details_utilization[k].toFixed(2)
          }
          // this.list3 = res.data.details
          this.list3 = details_arr
          var xData = []
          var timeList = {
            utilization: [],
          }
          var list = {
            utilization: '利用率（utilization）',
          }
          res.data.list.forEach((item, index) => {
            var time = new Date(item.createDate)
            xData.push(this.getTime(time))
            timeList.utilization.push(item.utilization.toFixed(2))
          })
          var seriesDate = []
          for (const k in list) {
            seriesDate.push({
              name: list[k],
              type: 'line',
              // stack: '总量',
              data: timeList[k],
            })
          }
          this.echartData3 = {
            id: 'cpuline3',
            type: 'green',
            xData: xData,
            legendData: ['利用率（utilization）'],
            seriesDate: seriesDate,
            unit: ' %',
          }
          break
        default:
          this.echartData3 = {
            id: 'cpuline3',
            type: 'green',
            xData: [],
            legendData: [],
            seriesDate: [],
            unit: ' %',
          }
          this.DlFlag3 = false
          this.reload_Dl3 = true
          break
      }
    },
    refreshDl3() {
      this.reload_Dl3 = false
      this.initList_findUtilization()
    },
    // 格式化时间
    getTime(date) {
      const Y = date.getFullYear()
      const M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var h = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()
      var m = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()
      var s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds()
      return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s // yyyy-MM-dd HH:mm:ss
    },
  },
  destroyed() {
    clearInterval(this.initInterval)
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/scss/cloudDetails.scss';
.el-col-lg-4-8 {
  width: 20%;
}
.el-col-xs-4-8 {
  width: 20%;
}
</style>
